
const http = require('http');
const fs = require('fs');
const url = require('url')
const template = require('art-template'); // art-template模板引擎


const server = http.createServer();
var wwwDir = 'C:/Users/Administrator/Desktop/H5/node/appsache/www';
var comments = [{
    name: '张三',
    age: '66'
}, {
    name: '李四',
    age: '66'
}];
server.on('request', function (req, res) {

    var parseObj=url.parse(req.url,true)
    var url = req.url;

    // 单独获取不包含字符串的路径部分(该路径不包含?之后的内容)
    var pathname=parseObj.pathname

    
    console.log(pathname.indexOf('/public/'));
    
    // 
    if (pathname === '/') {
        console.log(pathname); // 反斜杠会转义

        fs.readFile(wwwDir + '/index.html', function (err, data) {
            if (err) {
                // console.log(666);
                return res.end('404 not found');
            }

            fs.readdir(wwwDir, function (err, files) {
                if (err) {
                    // console.log(err);
                    return res.end('Can not find www dir');
                } // console.log(files);

            });
            var htmlStr = template.render(data.toString(), {
                comments: comments
            }); // data = data.toString()
            // data = data.replace('输入16进制颜色', '不输入')
            // res.end(data)
            // console.log(htmlStr);

            res.end(htmlStr);
        });
    } else if (pathname === '/pinglun') {

        res.end(JSON.stringify(parseObj.query))
        return res.end('555')
    } else if (pathname.indexOf('/public/') === 0) {
        // 获取静态资源
        // 需要加点，表示当前目录
        fs.readFile('.' + pathname, function (err, data) {
            if (err) {
                console.log(err);
                return res.end('404 Not Found');
            } // console.log(data.toString());


            res.end(data);
        });
    } else if (pathname === '/post') {

        fs.readFile(wwwDir + '/index.html', function (err, data) {
            if (err) {
                // console.log(666);
                return res.end('404 not found');
            }

            fs.readdir(wwwDir, function (err, files) {
                if (err) {
                    // console.log(err);
                    return res.end('Can not find www dir');
                }

                console.log(files);
            });
            data = data.toString();
            data = data.replace('输入16进制颜色', '不输入');
            res.end(data);
        });
    } else {
        // 404界面
        fs.readFile('./view/error.html', function (err, data) {
            if (err) {
                console.log(err);
                return res.end('404 Not Found');
            } // console.log(data.toString());


            res.end(data);
        });
    } // console.log(req.pathname);

});



server.listen(3000, function () {
    console.log('running');
});
